#include "time_utils.h"
#include "stm32f1xx_hal.h"


__IO uint32_t m, tms, u, t_0;


//us-ms*1000
void delay(uint32_t _ms)
{
    t_0 = micros();
    while (micros() - t_0 < _ms * 1000)
        __NOP();
}

//意思是28个tick为1us
void delayMicroSeconds(uint32_t _us)
{
    _us *= 28; // Need to be tuned for different CPU
    while (_us--) __NOP();
}


__STATIC_INLINE uint32_t LL_SYSTICK_IsActiveCounterFlag()
{
    return ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == (SysTick_CTRL_COUNTFLAG_Msk));//16位为1返回1，代表当前值已递减到0，因为递减到0时SysTick->CTRL的16位置1
}

//返回当前运行us
uint64_t micros()
{
    /* Ensure COUNTFLAG is reset by reading SysTick control and status register */
    LL_SYSTICK_IsActiveCounterFlag();
    m = HAL_GetTick();//一次中断加一，即1ms
    tms = SysTick->LOAD + 1;//重载值加1
    u = tms - SysTick->VAL;//重载值减当前值
    if (LL_SYSTICK_IsActiveCounterFlag())//递减到0时
    {
        m = HAL_GetTick();//已运行的tick
        u = tms - SysTick->VAL;//重载值减当前值
    }
    return (m * 1000 + (u * 1000) / tms);//已运行的ms加正在运行的重载计数u/tms(ms)
}

//返回目前ms
uint32_t millis()
{
    return HAL_GetTick();
}


